package com.idbk.chargestation.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.charge.ActivityDoubleGun;
import com.idbk.chargestation.activity.charge.ActivityLock;
import com.idbk.chargestation.activity.charge.ActivitySingleGun;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonMyBookResult;
import com.idbk.chargestation.bean.JsonMyBooking;
import com.idbk.chargestation.bean.JsonMyBookingItem;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.dialog.DialogResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.util.UIUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 预约界面
 *
 * @author zhx
 */
public class FragmentBooking extends Fragment implements OnClickListener {

    public View mView;
    private Context mContext;

    public RelativeLayout mLayoutInf;
    public TextView mResidual, mPile, mEndTime, mCost, mStartTime, mPoint;
    public TextView mCancle, mScan;
    private ProgressDialog mDialog;
    private ProgressDialog mMainProgressDialog;
    private StringRequest mRequest;
    private JsonMyBooking mResults;
    private LinearLayout mLayoutEmpty, mLayoutError;
    public String mSn;
    private final static String STR_RESULT_CANCEL_RESPEAK = "预约的金额：<font color='#ff0000'>%.2f</font>元，实际消费：<font color='#ff0000'>%.2f</font>元";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_booking, container, false);

        setupView();

        setupData();

        return mView;
    }

    public void setupView() {
        mContext = getActivity();

        mLayoutEmpty = (LinearLayout) mView.findViewById(R.id.tj_empty_view);
        mLayoutError = (LinearLayout) mView.findViewById(R.id.tj_error_view);
        mLayoutError.setOnClickListener(this);

        mLayoutInf = (RelativeLayout) mView.findViewById(R.id.layout_inf);
        mResidual = (TextView) mView.findViewById(R.id.residual_time);
        mPile = (TextView) mView.findViewById(R.id.textview_pile);
        mEndTime = (TextView) mView.findViewById(R.id.textview_endtime);
        mCost = (TextView) mView.findViewById(R.id.textview_cost);
        mStartTime = (TextView) mView.findViewById(R.id.textview_starttime);
        mPoint = (TextView) mView.findViewById(R.id.textview_east);

        mCancle = (TextView) mView.findViewById(R.id.textview_action_left);
        mCancle.setOnClickListener(this);
        mScan = (TextView) mView.findViewById(R.id.textview_action_right);
        mScan.setOnClickListener(this);

    }

    public void setupData() {
        mDialog = ProgressDialog.show(mContext, null, "加载中...", true, true, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mRequest != null) {
                    mRequest.cancel();
                }
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        //向服务器请求数据
        mRequest = ChargeStationAPI.getMyBespeak(mResponse);
    }

    private void bindData(String pointName, int remainMinutes, int pileNum, String endTime, double bespeakMoney, Date startTime) {
        mPoint.setText(pointName);
        String residual = remainMinutes + "";
        mResidual.setText(residual);
        String pile = "预约电桩: " + String.format(Locale.CHINA, "#%02d", pileNum);
        mPile.setText(pile);
        String end = "充电时间: " + endTime;
        mEndTime.setText(end);
        mCost.setText("预约费用:  " + bespeakMoney + "元");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String strStart = sdf.format(startTime) + " 预约成功";
        mStartTime.setText(strStart);

    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            mResults = GsonUtils.toBean(JsonMyBooking.class, response);
            if (BaseActivity.handleResponseStatus(getActivity(), mResults)) {
                if (mResults.items == null || mResults.items.size() <= 0) {
                    UIUtil.showEmpty(mLayoutEmpty, mLayoutError);
                    mLayoutInf.setVisibility(View.GONE);

                } else {
                    UIUtil.hideAll(mLayoutEmpty, mLayoutError);
                    mLayoutInf.setVisibility(View.VISIBLE);
                    JsonMyBookingItem item = mResults.items.get(0);
                    mSn = item.pileSn;
                    bindData(
                            item.pointName,
                            item.getBookRemainMinutes(),
                            item.pileNum,
                            item.getSimpleEndTime(),
                            item.bespeakMoney,
                            item.startTime);
                }
            }

        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //显示文字
            UIUtil.showNetError(mLayoutEmpty, mLayoutError);
            mLayoutInf.setVisibility(View.GONE);
        }

        @Override
        public void onEFinish() {
            //关闭 等待窗
            mDialog.dismiss();
        }

    };

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tj_error_view:
                setupData();
                break;
            case R.id.textview_action_left:
                cancleMyBook();
                break;
            case R.id.textview_action_right:
                gotoCharge();
                break;
            default:
                break;
        }

    }

    private void cancleMyBook() {
        new AlertDialog.Builder(mContext)
                .setMessage("你确定要取消当前预约吗？")
                .setNegativeButton(R.string.common_cancel, null)
                .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mResults != null && mResults.items != null && mResults.items.size() > 0) {
                            showMainProgressDialog(true);
                            mRequest = ChargeStationAPI.revokePileBespeak(mResults.items.get(0).pileSn, cancleResponse);
                        } else {
                            Toast.makeText(mContext, "参数错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create()
                .show();
    }

    public void showMainProgressDialog(final boolean canCancel) {
        mMainProgressDialog = ProgressDialog.show(mContext, null, "提交中...", true, true,
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (canCancel) {
                            if (mRequest != null) {
                                mRequest.cancel();
                            }
                        }
                    }
                });
    }


    private final EHttpResponse cancleResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            mMainProgressDialog.dismiss();
            JsonMyBookResult result = GsonUtils.toBean(JsonMyBookResult.class, response);
            if (BaseActivity.handleResponseStatus(getActivity(), result)) {
                String mBill = String.format(Locale.CHINA,
                        STR_RESULT_CANCEL_RESPEAK,
                        result.bespeakMoney,
                        result.expenseMoney);

                final DialogResult dialog = new DialogResult(getContext(), true, "取消成功", mBill);
                dialog.show();

                UIUtil.showEmpty(mLayoutEmpty, mLayoutError);
                mLayoutInf.setVisibility(View.GONE);
            }

        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            if (mMainProgressDialog != null) {
                mMainProgressDialog.dismiss();
            }
            final DialogResult mErrorDialog = new DialogResult(getContext(), false, "取消失败", "请检查网络后重新取消");
            mErrorDialog.show();
        }

        @Override
        public void onEFinish() {
            //关闭 等待窗
            mMainProgressDialog.dismiss();
        }

    };

    private void gotoCharge() {
        mDialog = ProgressDialog.show(mContext, null, "加载中...", true, true, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mRequest != null) {
                    mRequest.cancel();
                }
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        //向服务器请求数据
        mRequest = APIForCharge.qrScan(mSn, new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                JsonQrScan result = GsonUtils.toBean(JsonQrScan.class, response);
                if (result.status == GlobalResult.TOKEN_INVALID.getStatus()) {
                    BaseActivity.jumpToLogin(getActivity(), true);

                } else if (result.status == GlobalResult.OK.getStatus()) {
                    mDialog.dismiss();
                    handleResult(result);

                } else {
                    Toast.makeText(mContext, "输出信息有误，扫码充电", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onEErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "无法获取服务器数据！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEFinish() {
                // TODO Auto-generated method stub
                super.onEFinish();
                mDialog.dismiss();
            }

        });
    }

    private void handleResult(JsonQrScan result) {
        if (result.isConnect) {
            if (result.groundLockNum > 0
                    && (result.lock1 == JsonPointPile.STATUS_LOCK || result.lock2 == JsonPointPile.STATUS_LOCK)
                    && (!result.isUnLocked)) {
                // 有地锁选择地锁
                Intent intent = new Intent(mContext,
                        ActivityLock.class);
                intent.putExtra(JsonQrScan.KEY, result);
                startActivity(intent);
                getActivity().finish();

            } else if (result.pileType == JsonPointPile.PILE_TYPE_DC_DOUBLE_GUN_ASYN
                    || result.pileType == JsonPointPile.PILE_TYPE_DC_DOUBLE_GUN_SYN
                    || result.pileType == JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_SINGLE_PHASE
                    || result.pileType == JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_THREE_PHASE) {
                // 双枪充电桩
                Intent intent = new Intent(mContext,
                        ActivityDoubleGun.class);
                intent.putExtra(JsonQrScan.KEY, result);
                startActivity(intent);
                getActivity().finish();

            } else if (result.pileType == JsonPointPile.PILE_TYPE_DC
                    || result.pileType == JsonPointPile.PILE_TYPE_AC_SINGLE_PHASE
                    || result.pileType == JsonPointPile.PILE_TYPE_AC_THREE_PHASE) {
                // 单枪充电桩
                Intent intent = new Intent(mContext,
                        ActivitySingleGun.class);
                intent.putExtra(JsonQrScan.KEY, result);
                startActivity(intent);
                getActivity().finish();

            } else {
                Toast.makeText(mContext, "错误:未知的充电桩类型！", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(mContext, result.message, Toast.LENGTH_LONG).show();
        }
    }

}
